package com.remoter.context.spring.bean;

import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

import com.remoter.api.configure.IConfiguration;
import com.remoter.api.configure.support.AbstractConfiguration;
import com.remoter.api.context.IContextService;
import com.remoter.api.context.support.Exporter;
import com.remoter.api.extension.support.ExtensionLoader;
import com.remoter.api.util.Final;

public class ProviderBean implements InitializingBean, DisposableBean, ApplicationListener<ApplicationEvent>, BeanNameAware{
	
	private transient String name;
	private String id;
	private Class<?> type;
	private Object proxy;
	private IContextService contextService;
	
	private int weight;
	private int executes;
	
	@Override
	public void setBeanName(String name){
		this.name = name;
	}

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		IConfiguration configuration = AbstractConfiguration.getConfiguration();
		this.contextService = ExtensionLoader.getService(IContextService.class,configuration.getOption(Final.O_SERVER_CONTEXT));
		Exporter exporter = this.contextService.createExporter(this.name,this.type,this.proxy);
		exporter.setWeight(this.weight);
		exporter.setExecutes(this.executes);
		if(null == this.contextService.getExporter(this.name,this.type)){
			this.contextService.attachExporter(exporter);
		}
	}

	@Override
	public void destroy() throws Exception {
		this.contextService.detachExporter(this.name,this.type);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Class<?> getType() {
		return type;
	}

	public void setType(Class<?> type) {
		this.type = type;
	}

	public Object getProxy() {
		return proxy;
	}

	public void setProxy(Object proxy) {
		this.proxy = proxy;
	}

	public int getWeight() {
		return weight;
	}

	public void setWeight(int weight) {
		this.weight = weight;
	}

	public int getExecutes() {
		return executes;
	}

	public void setExecutes(int executes) {
		this.executes = executes;
	}
	
}